package com.example.njut;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class WeatherActivity extends AppCompatActivity {
    private EditText inputCity;
    private Button button1;
    private Button button2;
    private TextView city;
    private TextView date;
    private TextView low;
    private TextView high;
    private TextView text_day;
    private TextView text_night;
    private TextView text_now;
    private TextView temp_now;

    LocationManager lm;

    ArrayList<Weather> arrayList1;
    ArrayList<NowWeather> arrayList2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);

        inputCity = (EditText) findViewById(R.id.inputCity);
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.exit);
        city = (TextView) findViewById(R.id.city);
        date = (TextView) findViewById(R.id.date);
        low= (TextView) findViewById(R.id.lowtemp);
        high = (TextView) findViewById(R.id.hightemp);
        text_day = (TextView) findViewById(R.id.dayWeather);
        text_night = (TextView) findViewById(R.id.nightWeather);
        text_now = (TextView) findViewById(R.id.nowWeather);
        temp_now = (TextView) findViewById(R.id.nowTemp);

        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!isGpsAble(lm)) {
            Toast.makeText(WeatherActivity.this, "请先打开位置信息！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 0);
            WeatherActivity.this.finish();
        }
        //通过GPS获取最近一次的位置信息
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location lc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        final String localCity = getLocalCity(lc);

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputCity = WeatherActivity.this.inputCity.getText().toString().trim();
                showWeather(inputCity);
                showNowWeather(inputCity);

            }
        });

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showWeather(localCity);
                showNowWeather(localCity);
                Toast.makeText(WeatherActivity.this,localCity,Toast.LENGTH_SHORT).show();
            }
        });
    }


    public void  show(){
        runOnUiThread(
                new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this,"请求发送失败！请重试",Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }
    private String getLocalCity(Location lc) {
        String thisCity = null;

        if(lc!=null){
            Geocoder ge = new Geocoder(WeatherActivity.this);
            List<Address> addList = null;
            try {
                //sb.append("当前城市:"+ge.getFromLocation(lc.getLatitude(),lc.getLongitude(),1).get(0).getFeatureName());
                addList = ge.getFromLocation(lc.getLatitude(),lc.getLongitude(),1);

            } catch (IOException e) {
                e.printStackTrace();
            }
            Address ad = addList.get(0);
            thisCity = ad.getLocality();

        }else{
            Toast.makeText(WeatherActivity.this, "定位失败", Toast.LENGTH_SHORT).show();
        }
        return thisCity;

    }
    private boolean isGpsAble(LocationManager lm){
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ?true:false;
    }

    private void showWeather( final String City){
        new Thread(){
            public void run(){
                try{
                    String path = "https://api.seniverse.com/v3/weather/daily.json?key=SIOCPBEqycrUpr70G&location="+
                            City+"&language=zh-Hans&unit=c&start=0&days=5";

                    URL url = new URL(path);

                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();

                    conn.setReadTimeout(500);
                    conn.setRequestMethod("GET");



                    if(conn.getResponseCode()==200 ){
                        InputStream in = conn.getInputStream();


                        String str = "";
                        int len = 0;
                        byte[] buffer = new byte[1024];



                        while((len=in.read(buffer))>0 ){
                            str+=new String(buffer,0,len);
                        }

                        arrayList1 = MyJson.getWeather(str);

                        runOnUiThread(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        city.setText(arrayList1.get(0).getCity());
                                        date.setText(arrayList1.get(0).getDate());
                                        low.setText(arrayList1.get(0).getLow());
                                        high.setText(arrayList1.get(0).getHigh());
                                        text_day.setText(arrayList1.get(0).getText_day());
                                        text_night.setText(arrayList1.get(0).getText_night());

                                    }
                                }
                        );
                    }else{
                        // Toast.makeText(WeatherActivity.this,"请求发送失败！请重试",Toast.LENGTH_SHORT).show();
                        show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }

    private void showNowWeather( final String City){
        new Thread(){
            public void run(){
                try{
                    String path = "https://api.seniverse.com/v3/weather/now.json?key=SIOCPBEqycrUpr70G&location="+
                            City+"&language=zh-Hans&unit=c";
                    URL url = new URL(path);

                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();

                    conn.setReadTimeout(500);
                    conn.setRequestMethod("GET");



                    if(conn.getResponseCode()==200 ){
                        InputStream in = conn.getInputStream();


                        String str = "";
                        int len = 0;
                        byte[] buffer = new byte[1024];



                        while((len=in.read(buffer))>0 ){
                            str+=new String(buffer,0,len);
                        }

                        arrayList2 = MyJson.getNowWeather(str);

                        runOnUiThread(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        text_now.setText(arrayList2.get(0).getText());
                                        temp_now.setText(arrayList2.get(0).getTemperature());
                                    }
                                }
                        );
                    }else{
                        // Toast.makeText(WeatherActivity.this,"请求发送失败！请重试",Toast.LENGTH_SHORT).show();
                        show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();

    }
}
/*弹幕随机颜色
* 天气预报显示天气实况
* 按钮直接获取当前定位城市天气*/
